pipeline {
    agent any

    parameters {
        booleanParam(name: 'DO_PULL', defaultValue: true, description: 'Whether to git pull (excluding jenkins folder)')
        booleanParam(name: 'DO_BUILD_MINIKUBE', defaultValue: true, description: 'Whether to run ./minikube-build.sh')
        booleanParam(name: 'DO_BUILD', defaultValue: false, description: 'Whether to run ./build.sh')
        booleanParam(name: 'DO_HELM_UPGRADE', defaultValue: true, description: 'Whether to run helm upgrade')
        string(name: 'BASE', defaultValue: '../../../..', description: 'Base directory of the project')
    }

    environment {
        BASE_DIR = "${params.BASE}"
    }

    stages {
        stage('Pull Code (Exclude jenkins/)') {
            when {
                expression { return params.DO_PULL }
            }
            steps {
                dir("${env.BASE_DIR}") {
                    echo "Pulling code, excluding 'jenkins/' directory..."

                    sh '''
                        # Initialize sparse-checkout if not already enabled
                        git rev-parse --is-inside-work-tree || exit 1
                        git config core.sparseCheckout true

                        # Setup sparse-checkout rules
                        echo "/*" > .git/info/sparse-checkout
                        echo "!/jenkins/" >> .git/info/sparse-checkout

                        # Apply sparse-checkout and pull latest
                        git read-tree -mu HEAD
                        git pull
                    '''
                }
            }
        }

        stage('Build for Minikube') {
            when {
                expression { return params.DO_BUILD_MINIKUBE }
            }
            steps {
                dir("${env.BASE_DIR}") {
                    echo "Running ./minikube-build.sh..."
                    sh './minikube-build.sh'
                }
            }
        }

        stage('Regular Build') {
            when {
                expression { return params.DO_BUILD }
            }
            steps {
                dir("${env.BASE_DIR}") {
                    echo "Running ./build.sh..."
                    sh './build.sh'
                }
            }
        }

        stage('Helm Upgrade') {
            when {
                expression { return params.DO_HELM_UPGRADE }
            }
            steps {
                dir("${env.BASE_DIR}") {
                    echo "Running helm upgrade... (install if not exist)"
                    sh 'helm upgrade app ./k8s/app || helm install app ./k8s/app'
                }
            }
        }
    }
}